package com.situ.mall.common.service.impl;

import com.situ.mall.common.entity.Attachment;
import com.situ.mall.common.mapper.AttachmentMapper;
import com.situ.mall.common.service.IAttachmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.common.vo.ResultVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 闫佳宁
 * @since 2023-09-13
 */
@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements IAttachmentService {

    @Value("${file.path}")
    private String filePath;

    @Value("${file.location}")
    private String fileLocation;
    @Override
    public ResultVO upload(MultipartFile file) {
        ResultVO vo = new ResultVO();
        //服务器为了防止文件重名定制了一个新名字
        String newFileName = System.currentTimeMillis() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//        路径
        try {
            File f = new File(fileLocation + newFileName);
//        把文件保存到服务器上的对应目录中
            file.transferTo(f);


            //保存到Attachment表一条数据
            Attachment att = new Attachment();
            att.setCreateTime(LocalDateTime.now());
            att.setFilePath(filePath+newFileName);
            att.setFileName(file.getOriginalFilename());
            att.setFileSize(file.getSize());
            baseMapper.insert(att);

            vo.setData(att);

            //返回文件的访问路径
        } catch (Exception e) {
            vo.setMsg("上传文件失败");
            System.out.println("上传文件失败");
        }
        return vo;
    }

    @Override
    public void bind(String attIds, Integer id, String source) {
        baseMapper.bind(attIds.split(","),id, source);
    }

    @Override
    public void clean() {
        baseMapper.clean();
    }

}
